<?php

function render_rules_to_js(){
	global $rules ;
	if(array_key_exists("js",$_GET) && $_GET["js"]!=""){
		header('Content-type:text/javascript;charset=utf-8');
		print "var rules = " . json_encode($rules) . ";" ;
	}
}

function get_current_action(){
	global $_SERVER , $rules ;
	$page = $_SERVER["SCRIPT_NAME"];
	$temp = explode("/",$page);
	$page = $temp[count($temp)-1];
	$temp = explode(".",$page);
	$page = $temp[0];
//	print $page ;
	if(array_key_exists($page,$rules)){
		return $page ;
	}
	return "";
}

function validate($regulation=""){
	global $_SERVER , $rules ;
	if(empty($regulation)){
		$action = get_current_action();
		if(array_key_exists($action,$rules)){
			$regulation = get_current_action() ;
		}
	}
	if(empty($regulation) || !is_array($regulation)){
		return true ;
	}
	$has_no_error = true ;
	for($i=0;$i<count($regulation);$i++){
		$rule = $regulation[$i];
		$field = $rule["field"] ;
		$input_name = str_replace("[]","",$field);
		$label = $rule["label"] ;
		$value = get($input_name);
		$validates = explode("|",$rule["rules"]);
		
		for($t=0;$t<count($validates);$t++){
			$validate = trim($validates[$t]);
			if("required" == $validate){
				if(is_array($value)){
					for($n=0;$n<count($value);$n++){
						if($value[$n] == ""){
							// render_js("parent.set_text('si_$input_name','不能为空');");
							$has_no_error = false ;
						}
					}
				}else if($input_name == $field){
					if($value == ""){
						// print_html($input_name . "-" . $value);
						render_js("parent.set_text('si_$input_name','不能为空');");
						$has_no_error = false ;
					}
				}
			}
			if(empty($value)){
				continue ;
			}
			if("int" == $validate){
				if(is_array($value)){
					for($n=0;$n<count($value);$n++){
						if(!is_int($value[$n]*1)){
							render_js("parent.set_text('si_$input_name','必须为整型');");
							$has_no_error = false ;
						}
					}
				}else if(!is_int($value*1)){
					render_js("parent.set_text('si_$input_name','必须为整型');");
					$has_no_error = false ;
				}
			}
		}
	}
	return $has_no_error ;
}


function reset_rule($action,$field,$new_rule){
	global $rules ;
	if(array_key_exists($action,$rules)){
		$matrix = &$rules[$action];
		for($i=0;$i<count($matrix);$i++){
			if($matrix[$i]["field"] == $field){
				$matrix[$i]["rules"] = $new_rule;
				return ;
			}
		}
	}
}

function get_validate_fields($action=""){
	global $rules ;
	if(empty($action)){
		$action = get_current_action() ;
	}
	$fields = array();
	print_html($action);
	if(array_key_exists($action,$rules)){
		$matrix = &$rules[$action];
		for($i=0;$i<count($matrix);$i++){
			array_push($fields,$matrix[$i]["field"]);
		}
	}
	return $fields ;
}